package com.flower8.service.impl;

import com.flower8.dao.MessageDao;
import com.flower8.dao.PointDao;
import com.flower8.dao.SysConfigDao;
import com.flower8.model.SysConfig;
import com.flower8.service.RedbagService;
import com.flower8.service.SysConfigService;
import com.flower8.sysconfig.constants.SysConstants;
import com.flower8.utils.CreateRadomSeat;
import com.flower8.utils.PageData;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

/**
 * @Description:
 * @Author: tanglin
 * @Date: 2019/11/18 15:13
 * @Version: 1.0
 */
@Slf4j
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private PointDao pointDao;
    @Autowired
    private RedbagService redbagService;

    @PostConstruct
    public void init() {
        log.info("项目启动中，加载数据开始");
        loadSysDict(false);
        log.info("项目启动中，加载数据完成");
    }

    private void loadSysDict(boolean reload) {
        log.info("++++++ 加载数据字典开始 ++++++");
        try {
            Map dictMap = stringRedisTemplate.opsForHash().entries("systemDictValue");
            if (reload) {
                if (dictMap != null) {
                    for (Object key : dictMap.keySet()) {
                        stringRedisTemplate.opsForHash().delete("systemDictValue", key);
                    }
                }
                dictMap = null;
            }
            if (dictMap == null) {
                PageData pd = new PageData();
                pd.put("start", 0);
                pd.put("length", 1000);
                List<Map> dictList = getAppDist(pd);
                for (Map map : dictList) {
                    stringRedisTemplate.opsForHash().put("systemDictValue", map.get("code"), map.get("values"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("++++++ 加载数据字典完成 ++++++");
    }

    /**
     * 查询App首页展示模块列表
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<SysConfig> getHomeModelList(PageData pd) throws Exception {
        return sysConfigDao.getHomeModelList(pd);
    }

    /**
     * 查询App首页展示模块数量
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public int getHomeModelListCount(PageData pd) throws Exception {
        return sysConfigDao.getHomeModelListCount(pd);
    }

    /**
     * 根据App首页展示模块的id查询
     *
     * @param pd
     * @return
     */
    @Override
    public SysConfig getHomeModelById(PageData pd) throws Exception {
        return sysConfigDao.getHomeModelById(pd);
    }

    /**
     * 更新app首页展示模块
     *
     * @param sysConfig
     * @throws Exception
     */
    @Override
    @Transactional
    public void updateHomeModel(SysConfig sysConfig) throws Exception {
        sysConfigDao.updateHomeModel(sysConfig);
    }

    /**
     * 删除app首页展示模块
     * @param id
     * @throws Exception
     */
    @Override
    @Transactional
    public void deleteHomeModel(long id) throws Exception {
        sysConfigDao.deleteHomeModel(id);
    }

    /**
     * 新增app首页展示模块
     * @param sysConfig
     * @throws Exception
     */
    @Override
    @Transactional
    public void addHomeModel(SysConfig sysConfig) throws Exception {
        sysConfigDao.addHomeModel(sysConfig);
    }

    /**
     * 后台管理系统配置信息
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> getAdminSysInfo() throws Exception {
        return sysConfigDao.getAdminSysInfo();
    }

    /**
     * 奖池充值记录表
     * @param map
     * @throws Exception
     */
    @Override
    @Transactional
    public void addAwardMoneyRecord(Map map) throws Exception {
        long uid = Long.parseLong(map.get("uid").toString());
        double redbgMoney = Double.parseDouble(map.get("money").toString()); //发送的红包金额
        //更新奖池金额
        Object obj = stringRedisTemplate.opsForValue().get("totalMoney");
        if(obj != null) {//奖池中有金额
            double oldMoney = Double.parseDouble(stringRedisTemplate.opsForValue().get("totalMoney").toString());
            double newMoney = redbgMoney;
            double total = newMoney + oldMoney;
            total = (double) Math.round(total * 100) / 100;
            //更新redis奖池数据
            stringRedisTemplate.opsForValue().set("totalMoney", String.valueOf(total));
            //更新数据库中的奖池
            sysConfigDao.updateAwardPool(total);
        }else{//奖池中无金额
            sysConfigDao.addAwardPool(redbgMoney);
            stringRedisTemplate.opsForValue().set("totalMoney",String.valueOf(redbgMoney));
        }

        //添加发红包记录
        sysConfigDao.addAwardMoneyRecord(map);
        //添加一条消息通知
        Map msgParam = new HashMap();
        msgParam.put("uid",uid);
        msgParam.put("type",1);
        msgParam.put("category",1);
        msgParam.put("contents","向红包池发送"+map.get("money").toString()+"元红包");
        msgParam.put("icon", SysConstants.MSG1);
        messageDao.addMsg(msgParam);
    }

    /**
     * 大转盘重新排座
     * @throws Exception
     */
    @Override
    public void newBigWheel() throws Exception {
        List<Map> res = null;
        try {
            res = redbagService.getGoodsList(2L);

            List<String> BigWheelList = CreateRadomSeat.radomBigWheel(res);
            //清除原始的redis中的大转盘排座
            stringRedisTemplate.opsForList().trim("BigWheelList",0,0);
            stringRedisTemplate.opsForList().leftPop("BigWheelList");
            //存放新的大转盘排座
            stringRedisTemplate.opsForList().rightPushAll("BigWheelList",BigWheelList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询奖池金额
     * @return
     * @throws Exception
     */
    @Override
    public double getAwardPool() throws Exception {
        return sysConfigDao.getAwardPool();
    }

    /**
     * 查询App数据字典配置
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> getAppDist(PageData pd) throws Exception {
        return sysConfigDao.getAppDist(pd);
    }

    /**
     * 查询App数据字典配置数量
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public int getAppDistCount(PageData pd) throws Exception {
        return sysConfigDao.getAppDistCount(pd);
    }

    /**
     * 新增App字典数据
     * @param param
     * @throws Exception
     */
    @Override
    @Transactional
    public void addAppDict(Map param) throws Exception {
        sysConfigDao.addAppDict(param);
        loadSysDict(true);
    }

    /**
     * 修改App字典数据
     * @param param
     * @throws Exception
     */
    @Override
    @Transactional
    public void updAppDict(Map param) throws Exception {
        sysConfigDao.updAppDict(param);
        loadSysDict(true);
    }

    /**
     * 删除App字典数据
     * @param id
     * @throws Exception
     */
    @Override
    @Transactional
    public void deleteAppDict(long id) throws Exception {
        sysConfigDao.deleteAppDict(id);
        loadSysDict(true);
    }

    /**
     * 通过app字典的id查询
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map getAppDictById(long id) throws Exception {
        return sysConfigDao.getAppDictById(id);
    }

    /**
     *根据code 查询字典
     * @param code
     * @throws Exception
     */
    @Override
    public Map getSysDist(String code)throws Exception {
        Map resMap = new HashMap();
        List<Map> res = sysConfigDao.getSysDist(code);

        for (Map map : res) {
            resMap.put(map.get("code").toString(),map.get("values").toString());
        }
        return resMap;
    }
}
